import { Component, Host, ChangeDetectorRef } from "@angular/core";
import { AppComponent } from "../../../../../../../app.component";
import { ActivatedRoute } from "@angular/router";
import { ReportingService } from "../../../../../reporting.service";
import { Subscription } from "rxjs";
import { UnscreenableModel } from "../../models/save/criteriaTemplateOutput.models";
import { CriteriaComponent } from "../../../criteria.component";
import { TemplateCriteriaModel } from "../../../../../models/templateCriteria.model";
import { CriteriaPermissionsComponent } from "../../../criteriaPermissions.component";

@Component({
    templateUrl: 'reportAll.component.html'
})
export class ReportAllComponent extends CriteriaPermissionsComponent {
    private sub: Subscription;
    private levelSub: Subscription;

    public listChecks: any[];
    public title: string;
    public riskRating: boolean;
    public level2Id: string;
    private level2ShortName: string;

    constructor(
        private cdRef: ChangeDetectorRef,
        private route: ActivatedRoute,
        private toolsService: ReportingService,
        @Host() private rootComponent: AppComponent,
        @Host() private criteriaComponent: CriteriaComponent) {
        super(cdRef);
    }

    ngOnInit() {
        this.sub = this.route.params.subscribe(param => {
            this.levelSub = this.toolsService.levels.subscribe(levels => {
                let level1: any = levels.find(x => x.id == param['lvl1']);
                this.riskRating = level1.name.indexOf('ESG Risk Rating') > -1;
                this.level2Id = param['lvl2'];                
                let level2: any = level1.childItems.find(x => x.id == this.level2Id);
                this.level2ShortName = level2.shortName;
                this.title = level2.name;
                //TODO: Do we really need this server call? Can't we used already cached levels? No. Coz this call returns additional data
                this.toolsService.getTemplateCriteria(null, null, level2.baseCriteria[0].id).subscribe(data => {                    
                    let name: string;
                    let type: number;
                    let result: any[] = [];
                    data.forEach(element => {                        
                        name = 'Value';
                        type = data[0].criteriaType;
                        if (type == 16) {
                            if (element.name.startsWith('CG - Rank'))
                                name = 'CG - Rank';
                            else if (element.name.startsWith('CG - Percentile'))
                                name = 'CG - Percentile';
                        }
                        else if ((type != 10 && type != 6 && type != 7) || !this.riskRating) {
                            let list = element.name.split('-');
                            name = list.length > 1 ? list[list.length - 1] : 'Value';
                        }

                        if (result.findIndex(x => x.name == name) == -1)
                            result.push({ name: name, isOn: false });
                    });
                    this.listChecks = result;
                    this.rootComponent.finishLoading();
                });
            });
        });
    }

    ngOnDestroy() {
        this.sub.unsubscribe();
        this.levelSub.unsubscribe();
    }

    public canSelect(): boolean {
        return this.listChecks && this.listChecks.findIndex(x => x.isOn == true) > -1;
    }

    public selectAll() {
        //call server to return all selected template criteria.
        this.toolsService.loadDataPointsForReport(this.level2Id, this.listChecks).subscribe(data => {            
            let selectedResult: UnscreenableModel[] = [];
            let selected: string[] = this.listChecks.filter(x => x.isOn).map(x => x.name);
            data.forEach(element => {                
                if (element.criteriaType == 4 && this.isEnabled(this.level2ShortName, element.criteriaEntityField.split(' ')[0])) {
                    var list = element.name.split("-");
                    var name = list.length > 1 ? list[list.length - 1] : "Value";
                    if (selected.indexOf(name) > -1)
                        selectedResult = this.createTemplateModel(element, selectedResult, false);
                }
                else if (element.criteriaType == 10) {
                    selectedResult = this.createTemplateModel(element, selectedResult, true);
                }
                else if (element.criteriaType == 0 && this.riskRating) {
                    if (element.name.indexOf('Weight') == -1 && element.name.indexOf('Sub-Industry Exposure Score') == -1)
                        selectedResult = this.createTemplateModel(element, selectedResult, true);
                }
                else {
                    if (selected.findIndex(x => x === 'Value' || element.name.startsWith(x + ' - ') || element.name.endsWith('-' + x)) > -1)
                        selectedResult = this.createTemplateModel(element, selectedResult, true);
                }
            });
            this.criteriaComponent.criteriaChanged.emit(selectedResult);
        });
    }

    private createTemplateModel(element: any, parent: UnscreenableModel[], checkClaim: boolean): UnscreenableModel[] {        
        if(!checkClaim || (checkClaim && this.isEnabled(this.level2ShortName, element.name))){                    
            
            let criteria: TemplateCriteriaModel = new TemplateCriteriaModel();
            criteria.id = element.id;
            criteria.name = element.name;
            criteria.criteriaType = element.criteriaType;
            criteria.isDataPoint = true;
            criteria.isOn = true;
            criteria.criteriaEntityField = element.criteriaEntityField;
            criteria.criteriaLevel2 = this.level2Id;
            let index = parent.findIndex(x=> x.criteriaLevel3Id == element.criteriaLevel3Id);
            if(index > -1)
                parent[index].isNotScreenableCriteriaItems.push(criteria);
            else
            {
                let model = new UnscreenableModel(element.name, this.level2Id, element.criteriaLevel3Id, element.criteriaType, [criteria]);
                if(element.criteriaType == 4)
                    model.claimSymbol = element.criteriaEntityField.split(' ')[0];                
                parent.push(model);
            }
        }
        return parent;
    }
}